/* Copyright (c) Huawei Technologies Co., Ltd. 2024-2025. All rights reserved.
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 * ===================================================================================================================*/
#include "graph/ascend_ir/generator/ascir_registry.h"
#include "common/checker.h"

#include "ascir_recovery_utils.h"
namespace ge {
graphStatus AscIrRecoveryUtils::RecoverOpDescIrDefinition(const OpDescPtr &desc) {
  IrDefinition ir_def;
  InitIrDefinitionsIfNeed(desc->GetType(), ir_def);

  if (!ir_def.has_ir_definition) {
    GELOGI("Op type:%s has no registered IR, maybe no need to recover.", desc->GetTypePtr());
    return ge::GRAPH_SUCCESS;
  }

  // ir_attr_names
  GE_ASSERT_GRAPH_SUCCESS(RecoverIrAttrNames(desc, ir_def),
                          "%s %s recover ir attr names failed.",
                          desc->GetNamePtr(),
                          desc->GetTypePtr());
  // ir input and output
  GE_ASSERT_GRAPH_SUCCESS(RecoverIrInputAndOutput(desc, ir_def),
                          "%s %s recover ir input and output failed.",
                          desc->GetNamePtr(),
                          desc->GetTypePtr());
  return GRAPH_SUCCESS;
}

void AscIrRecoveryUtils::InitIrDefinitionsIfNeed(const string &op_type, RecoverIrUtils::IrDefinition &ir_def) {
  if (ir_def.inited) {
    return;
  }
  const auto &ir_defs = ascir::AscirRegistry::GetInstance().GetAll();
  const auto iter = ir_defs.find(op_type);
  if (iter == ir_defs.end()) {
    GELOGW("Failed to find ir infos for type %s", op_type.c_str());
    ir_def.has_ir_definition = false;
    ir_def.inited = true;
    return;
  }
  std::vector<std::string> attr_names;
  for (const auto &attr_def:  iter->second.attr_defs) {
    attr_names.emplace_back(attr_def.name);
  }
  ir_def.attr_names = attr_names;
  ir_def.inputs = iter->second.input_defs;
  ir_def.outputs = iter->second.output_defs;
  ir_def.has_ir_definition = true;
  ir_def.inited = true;
}
}